package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.*;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ESConstant;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.feign.groupsendjob.GroupSendChildidPushDto;
import com.uzai.console.dto.feign.groupsendjob.NewGroupSendMsgDto;
import com.uzai.console.dto.groupsendjob.GroupSendJobConditionOrderDto;
import com.uzai.console.dto.groupsendjob.GroupSendJobUserQueryParaDto;
import com.uzai.console.dto.rocketmq.friendrequest.DeleteUserDto;
import com.uzai.console.dto.rocketmq.groupsendjob.GroupSendMsgDto;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.dto.wechatprivate.wxcontacts.*;
import com.uzai.console.dto.feign.wxcontacts.WxContactsRegisterDto;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.GroupSendJob;
import com.uzai.console.entity.WxqContactRefresh;
import com.uzai.console.entity.es.EsWorkWxContacts;
import com.uzai.console.entity.es.EsWxContacts;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.WxContactsFeignService;
import com.uzai.console.service.groupsendjob.GroupSendJobConditionService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.wechatprivate.WxContactsService;
import com.uzai.console.vo.device.DeviceInfoSimpleVo;
import com.uzai.console.vo.exportinfo.ExportAmountVo;
import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsBatchRefreshVo;
import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsInfoVo;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 个人微信-微信通讯录
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxContactsServiceImpl implements WxContactsService {

    Logger logger = LoggerFactory.getLogger(WxContactsServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private WxContactsFeignService wxContactsFeignService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private PyqExpressionMapper pyqExpressionMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private GroupSendJobConditionService groupSendJobConditionService;
    @Autowired
    private WxqContactRefreshMapper wxqContactRefreshMapper;

    /**
     * 查询微信通讯录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxContactsQuery
     * @param tuominFlag 是否需要脱敏
     * @return null
     */
    public Page<WxContactsInfoVo> findWxContactsList(WxContactsQuery wxContactsQuery, Boolean tuominFlag){
        //新建返回到页面的LIST对象
        List<WxContactsInfoVo> wxContactsInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxContactsInfoVo> page = new Page<>();
        wxContactsQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxContactsQuery.getMerId())));

        //好友类型(0-个人微信；1-微信群)
        if(wxContactsQuery.getUserType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("userType", wxContactsQuery.getUserType()));
        }

        //高亮字段
        String highlightField = null;

        //微信昵称
        if(StringUtils.isNotBlank(wxContactsQuery.getNick())){
//            boolQuery_or.should(QueryBuilders.matchQuery("nick", wxContactsQuery.getNick()));
//            boolQuery_or.should(QueryBuilders.termQuery("nick.raw", wxContactsQuery.getNick()));

            //支持中文分词
            boolQuery_or.should(QueryBuilders.matchQuery("nick", wxContactsQuery.getNick()));

            //支持数字和英文
            boolQuery_or.should(QueryBuilders.wildcardQuery("nick", "*"+wxContactsQuery.getNick() +"*"));

            //highlightField = "nick";
        }

        //微信id
        if(StringUtils.isNotBlank(wxContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxContactsQuery.getWxid()));
            //highlightField = "wxid";
        }

        //微信号
        if(StringUtils.isNotBlank(wxContactsQuery.getWxno())){
            boolQuery_and.must(QueryBuilders.termQuery("wxno",wxContactsQuery.getWxno()));
            //highlightField = "wxno";
        }


        //机器人唯一ID
        if(wxContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxContactsQuery.getDeviceUniqueIdList() != null && wxContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxContactsQuery.getDeviceUniqueIdList()));
        }

        //最后群发消息开始时间
        if(wxContactsQuery.getLastGroupSendTimeStart() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").gte(wxContactsQuery.getLastGroupSendTimeStart()));
        }

        //最后群发消息结束时间
        if(wxContactsQuery.getLastGroupSendTimeEnd() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lte(wxContactsQuery.getLastGroupSendTimeEnd()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxContactsQuery.getBusyGroupSendMsgTime()));
        }

        //备注
        if(StringUtils.isNotBlank(wxContactsQuery.getRemark())){
            //boolQuery_and.must(QueryBuilders.matchPhraseQuery("remark", wxContactsQuery.getRemark()));
            //支持中文分词
            boolQuery_or.should(QueryBuilders.matchQuery("remark", wxContactsQuery.getRemark()));
            //支持数字和英文
            boolQuery_or.should(QueryBuilders.wildcardQuery("remark", "*"+wxContactsQuery.getRemark() +"*"));

        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //备注列表(匹配任何一个都算)
        List<String> remarkList = wxContactsQuery.getRemarkList();
        if(remarkList != null && remarkList.size() > 0){
            for (String remark : remarkList) {
                boolQuery_or.should(QueryBuilders.matchPhraseQuery("remark", remark));
            }
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));

        //判断是否需要脱敏
        if(tuominFlag == null){
            tuominFlag = false;
        }
        String cmstype_wxcontacts_wxid_verified =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_WXCONTACTS_WXID_VERIFIED, wxContactsQuery.getMerId()));
        if(StringUtils.isNotBlank(cmstype_wxcontacts_wxid_verified)){
            tuominFlag = false;
        }


        //通过查询运营商其他索引分片获取分片索引
        String esName = EsIndexName.UZAI_WX_CONTACTS;
        String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxContactsQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(mechantOtherEsIndexName, searchSourceBuilder, wxContactsQuery.getSize(), wxContactsQuery.getFromIndex(), null, null, highlightField, wxContactsQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxContactsInfoVo wxContactsInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxContactsInfoVo.class);

                //查询机器人信息
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxContactsInfoVo.getDeviceUniqueId(), wxContactsInfoVo.getMerId());
                if(deviceWechatInfo != null){
                    wxContactsInfoVo.setDeviceName(deviceWechatInfo.getDeviceName());
                    wxContactsInfoVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
                }

                //会员信息
                if(StringUtils.isNotBlank(wxContactsInfoVo.getWxid())){
                    User user = userService.findUserInfoByWxid(wxContactsInfoVo.getMerId(), wxContactsInfoVo.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
                    if(user != null){
                        wxContactsInfoVo.setUserId(user.getId());
                        wxContactsInfoVo.setBalance(user.getBalance());
                        wxContactsInfoVo.setIntegral(user.getIntegral());
                    }
                }

                //是否脱敏处理
                if(tuominFlag){
                    wxContactsInfoVo.setWxid(DesensitizeUtil.around(Tools.getStr(wxContactsInfoVo.getWxid()),3,3));
                    wxContactsInfoVo.setWxno(DesensitizeUtil.around(Tools.getStr(wxContactsInfoVo.getWxno()),3,3));
                }

                wxContactsInfoVoList.add(wxContactsInfoVo);
            }
        }


        //返回到页面分页对象
        page.setRecords(wxContactsInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 查询微信通讯录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxContactsQuery
     * @return null
     */
    public Page<EsWxContacts> findWxContactsListForGroupSendMsg(WxContactsQuery wxContactsQuery){
        //新建返回到页面的LIST对象
        List<EsWxContacts> esWxContactsList = new ArrayList<>();

        //执行分页查询对象
        Page<EsWxContacts> page = new Page<>();
        wxContactsQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxContactsQuery.getMerId())));

        //好友类型(0-个人微信；1-微信群)
        if(wxContactsQuery.getUserType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("userType", wxContactsQuery.getUserType()));
        }

        //高亮字段
        String highlightField = null;

        //微信昵称
        if(StringUtils.isNotBlank(wxContactsQuery.getNick())){
            boolQuery_or.should(QueryBuilders.matchQuery("nick", wxContactsQuery.getNick()));
            boolQuery_or.should(QueryBuilders.termQuery("nick.raw", wxContactsQuery.getNick()));
            highlightField = "nick";
        }

        //微信id
        if(StringUtils.isNotBlank(wxContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxContactsQuery.getWxid()));
            //highlightField = "wxid";
        }

        //微信号
        if(StringUtils.isNotBlank(wxContactsQuery.getWxno())){
            boolQuery_and.must(QueryBuilders.termQuery("wxno",wxContactsQuery.getWxno()));
            //highlightField = "wxno";
        }

        //机器人唯一ID
        if(wxContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxContactsQuery.getDeviceUniqueIdList() != null && wxContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxContactsQuery.getDeviceUniqueIdList()));
        }

        //最后群发消息开始时间
        if(wxContactsQuery.getLastGroupSendTimeStart() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").gte(wxContactsQuery.getLastGroupSendTimeStart()));
        }

        //最后群发消息结束时间
        if(wxContactsQuery.getLastGroupSendTimeEnd() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lte(wxContactsQuery.getLastGroupSendTimeEnd()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxContactsQuery.getBusyGroupSendMsgTime()));
        }

        //备注
        if(StringUtils.isNotBlank(wxContactsQuery.getRemark())){
            boolQuery_and.must(QueryBuilders.matchPhraseQuery("remark", wxContactsQuery.getRemark()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //备注列表(匹配任何一个都算)
        List<String> remarkList = wxContactsQuery.getRemarkList();
        if(remarkList != null && remarkList.size() > 0){
            for (String remark : remarkList) {
                boolQuery_or.should(QueryBuilders.matchPhraseQuery("remark", remark));
            }
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));

        //通过查询运营商其他索引分片获取分片索引
        String esName = EsIndexName.UZAI_WX_CONTACTS;
        String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxContactsQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(mechantOtherEsIndexName, searchSourceBuilder, wxContactsQuery.getSize(), wxContactsQuery.getFromIndex(), null, null, highlightField, wxContactsQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
                esWxContactsList.add(esWxContacts);
            }
        }

        //返回到页面分页对象
        page.setRecords(esWxContactsList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 删除通讯录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxContactsIdListDto
     * @return null
     */
    @Transactional
    public void deleteWxContacts(WxContactsIdListDto wxContactsIdListDto){

        List<String> idList = wxContactsIdListDto.getIdList();

        if(idList == null | idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        for (String id : idList){
            //查询微信通讯录
            //通过查询运营商其他索引分片获取分片索引
            String esName = EsIndexName.UZAI_WX_CONTACTS;
            String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxContactsIdListDto.getMerId());
            Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, id, null);
            WxContactsInfoVo wxContactsInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxContactsInfoVo.class);
            if(wxContactsInfoVo != null){
                //删除通讯录
                elasticsearchUtilGroupMsg.deleteDataById(mechantOtherEsIndexName, id);

                //发送MQ消息
                MsgDto<DeleteUserDto> msgDto = new MsgDto<>();
                DeleteUserDto deleteUserDto = new DeleteUserDto();
                deleteUserDto.setWxid(wxContactsInfoVo.getWxid());
                msgDto.setContent(deleteUserDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(wxContactsInfoVo.getDeviceType());
                msgDto.setDeviceUniqueId(wxContactsInfoVo.getDeviceUniqueId());
                msgDto.setMerId(wxContactsInfoVo.getMerId());
                msgDto.setMsgType(MessageFuncEnum.DELETE_USER.getValue());
                noticeMsgPushProducerService.deleteUser(msgDto);
            }
        }

        try {
            //解决ES延时删除
            Thread.sleep(1000);
        }catch (Exception e){

        }


    }

    /**
     * 单个发送消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxContactsSendMessageDto
     * @return null
     */
    public void sendMessage(WxContactsSendMessageDto wxContactsSendMessageDto){

        if(StringUtils.isBlank(wxContactsSendMessageDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        if(StringUtils.isBlank(wxContactsSendMessageDto.getMessage())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入消息内容");
        }

        try {
            //查询微信通讯录
            //通过查询运营商其他索引分片获取分片索引
            String esName = EsIndexName.UZAI_WX_CONTACTS;
            String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxContactsSendMessageDto.getMerId());
            Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, wxContactsSendMessageDto.getId(), null);
            WxContactsInfoVo wxContactsInfoVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxContactsInfoVo.class);
            if (wxContactsInfoVo != null) {
                //发送MQ消息
                MsgDto<NoticeMsgDto>  msgDto = new MsgDto<>();
                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                noticeMsgDto.setBizUserId(wxContactsInfoVo.getWxid());
                String msg = Tools.getStr(wxContactsSendMessageDto.getMessage());
                noticeMsgDto.setContent(msg.replace("[昵称]", wxContactsInfoVo.getNick()));
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(wxContactsInfoVo.getNick());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(wxContactsInfoVo.getDeviceType());
                msgDto.setDeviceUniqueId(wxContactsInfoVo.getDeviceUniqueId());
                msgDto.setMerId(wxContactsInfoVo.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }catch (Exception e){
            logger.error("向通讯录好友发送消息出现异常：{}"+ e.getMessage());
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息失败");
        }
    }

    /**
     * 通讯录注册
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxContactsIdDto
     * @return null
     */
    public void register(WxContactsIdDto wxContactsIdDto){

        if(StringUtils.isBlank(wxContactsIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询微信通讯录
        //通过查询运营商其他索引分片获取分片索引
        String esName = EsIndexName.UZAI_WX_CONTACTS;
        String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxContactsIdDto.getMerId());
        Map<String, Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(mechantOtherEsIndexName, wxContactsIdDto.getId(), null);
        WxContactsInfoVo wxContactsInfoVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxContactsInfoVo.class);
        if (wxContactsInfoVo != null) {
            //会员信息
            if (StringUtils.isNotBlank(wxContactsInfoVo.getWxid())) {
                User user = userService.findUserInfoByWxid(wxContactsInfoVo.getMerId(), wxContactsInfoVo.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
                if (user == null) {//没有找到会员信息，才注册
                    DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxContactsInfoVo.getDeviceUniqueId(), wxContactsInfoVo.getMerId());
                    if (deviceWechatInfo != null) {
                        //调用注册接口
                        WxContactsRegisterDto wxContactsRegisterDto = new WxContactsRegisterDto();
                        wxContactsRegisterDto.setMerId(wxContactsInfoVo.getMerId());
                        wxContactsRegisterDto.setDeviceId(wxContactsInfoVo.getDeviceId());
                        wxContactsRegisterDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                        wxContactsRegisterDto.setDeviceUniqueId(wxContactsInfoVo.getDeviceUniqueId());
                        wxContactsRegisterDto.setHeadImg(wxContactsInfoVo.getHimg());
                        wxContactsRegisterDto.setNickName(wxContactsInfoVo.getNick());
                        wxContactsRegisterDto.setWxid(wxContactsInfoVo.getWxid());
                        UzaiRespVo<Boolean> uzaiRespVo =  wxContactsFeignService.userreg2(wxContactsRegisterDto);
                        logger.info("---通讯录注册会员---wxContactsRegisterDto={}, uzaiRespVo={}",JSONObject.toJSONString(wxContactsRegisterDto), JSONObject.toJSONString(uzaiRespVo));
                    }
                }
            }
        }
    }

    /**
     * 刷新通讯录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void refreshWxContacts(WxContactsRefreshDto wxContactsRefreshDto){

        if(wxContactsRefreshDto.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxContactsRefreshDto.getDeviceUniqueId(), wxContactsRefreshDto.getMerId());

        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人不存在");
        }

        //测试服方便测试，抛弃5分钟限流
        if(wxContactsRefreshDto.getMerId() != 1547482020152213506L) {
            String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.WXCONTACTS_REFRESH, wxContactsRefreshDto.getMerId(), wxContactsRefreshDto.getDeviceUniqueId()));
            if (StringUtils.isNotBlank(val)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "5分钟只允许同一个机器人请求一次");
            }
        }

        //往reids插入本次下载，允许5分钟请求一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.WXCONTACTS_REFRESH, wxContactsRefreshDto.getMerId(), wxContactsRefreshDto.getDeviceUniqueId()),wxContactsRefreshDto.getDeviceUniqueId()+"",5, TimeUnit.MINUTES);

        //发送MQ消息
        MsgDto<Object> msgDto = new MsgDto<>();
        msgDto.setContent(null);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(wxContactsRefreshDto.getDeviceUniqueId());
        msgDto.setMerId(wxContactsRefreshDto.getMerId());
        msgDto.setMsgType(MessageFuncEnum.GET_MAIL_LIST_REQ.getValue());
        noticeMsgPushProducerService.updateWxContacts(msgDto);

        //修改机器人更新通讯录时间
        deviceWechatInfoMapper.updateRefreshWxcontactsTime(deviceWechatInfo.getId(), DateUtil.getNowTime());
    }

    /**
     * 批量刷新通讯录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public WxContactsBatchRefreshVo batchRefreshWxContacts(WxContactsBatchRefreshDto wxContactsBatchRefreshDto){

        WxContactsBatchRefreshVo wxContactsBatchRefreshVo = new WxContactsBatchRefreshVo();
        List<DeviceInfoSimpleVo> deviceInfoSimpleVoList = new ArrayList<>();
        wxContactsBatchRefreshVo.setErrorList(deviceInfoSimpleVoList);

        List<Long> deviceUniqueIdList = wxContactsBatchRefreshDto.getDeviceUniqueIdList();
        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        if(wxContactsBatchRefreshDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择刷新类型");
        }

        int now = DateUtil.getNowTime();

        for (Long deviceUniqueId : deviceUniqueIdList) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueId, wxContactsBatchRefreshDto.getMerId());
            if(deviceWechatInfo != null){
                //查询此机器人是否存在列表中
                WxqContactRefresh wxqContactRefresh_old = wxqContactRefreshMapper.selectByDeviceId(deviceWechatInfo.getDeviceId());
                if(wxqContactRefresh_old == null || wxqContactRefresh_old.getStatus() == 2){//为空或者状态为2，则新增加
                    //如果存在且完成状态，且先删除，在添加
                    if(wxqContactRefresh_old != null){
                        wxqContactRefreshMapper.deleteById(wxqContactRefresh_old.getId(), wxqContactRefresh_old.getMerId());
                    }
                    WxqContactRefresh wxqContactRefresh = new WxqContactRefresh();
                    wxqContactRefresh.setId(IdWorker.getId());
                    wxqContactRefresh.setMerId(wxContactsBatchRefreshDto.getMerId());
                    wxqContactRefresh.setType(wxContactsBatchRefreshDto.getType());
                    wxqContactRefresh.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                    wxqContactRefresh.setDeviceUniqueId(deviceUniqueId);
                    wxqContactRefresh.setDeviceId(deviceWechatInfo.getDeviceId());
                    wxqContactRefresh.setStatus(0); //未开始
                    wxqContactRefresh.setSendTime(0);
                    wxqContactRefresh.setCreateTime(now);
                    wxqContactRefresh.setUpdateTime(now);
                    wxqContactRefreshMapper.insert(wxqContactRefresh);
                }else{ //存在不允许添加,返回给前端页面
                    DeviceInfoSimpleVo deviceInfoSimpleVo = new DeviceInfoSimpleVo();
                    BeanUtils.copyProperties(deviceWechatInfo, deviceInfoSimpleVo);
                    deviceInfoSimpleVoList.add(deviceInfoSimpleVo);
                }
//
//                //发送MQ消息
//                MsgDto<Object> msgDto = new MsgDto<>();
//                msgDto.setContent(null);
//                msgDto.setId(IdWorker.getId());
//                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
//                msgDto.setDeviceUniqueId(deviceUniqueId);
//                msgDto.setMerId(wxContactsBatchRefreshDto.getMerId());
//                msgDto.setMsgType(MessageFuncEnum.GET_MAIL_LIST_REQ.getValue());
//                noticeMsgPushProducerService.updateWxContacts(msgDto);
//
//                //修改机器人更新通讯录时间
//                deviceWechatInfoMapper.updateRefreshWxcontactsTime(deviceWechatInfo.getId(), DateUtil.getNowTime());
            }
        }
        return wxContactsBatchRefreshVo;
    }

    /**
     * 根据单个机器人群发消息(异步)
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param addBatchSendMessageTaskDto
     * @return null
     */
    @Async("taskExecutor")
    public void groupSendMsgByDeviceUniqueId(AddBatchSendMessageTaskDto addBatchSendMessageTaskDto){
        WxContactsQuery wxContactsQuery = addBatchSendMessageTaskDto.getWxContactsQuery();
        wxContactsQuery.setMerId(addBatchSendMessageTaskDto.getMerId());
        GroupSendJob groupSendJobParent = addBatchSendMessageTaskDto.getGroupSendJobParent();
        groupSendJobParent.setMerId(addBatchSendMessageTaskDto.getMerId());
        if(wxContactsQuery == null){//判断条件是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; wechatUserQuery is null");
            return;
        }
        if(wxContactsQuery.getDeviceUniqueId() == null){//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return;
        }
        if(groupSendJobParent == null){//主线程不存在
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParent is null");
            return;
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxContactsQuery.getDeviceUniqueId(), addBatchSendMessageTaskDto.getMerId());
        if(deviceWechatInfo == null){
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + wxContactsQuery.getDeviceUniqueId());
            return;
        }

        //查询总用户数
        int pageCurrent = 1; //从第一页开始查询
        wxContactsQuery.setCurrent(pageCurrent);
        wxContactsQuery.setSize(10);

        Page<EsWxContacts> wxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
        if(wxContactsPage != null && wxContactsPage.getRecords() != null && wxContactsPage.getRecords().size() > 0){
            //添加群发消息子任务
            Integer now = DateUtil.getNowTime();
            //添加群发消息主任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(groupSendJobParent.getId()); //主任务id
            groupSendJob_son.setMerId(addBatchSendMessageTaskDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wxContactsQuery.getDeviceUniqueId());
            groupSendJob_son.setName(groupSendJobParent.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.PRIVATE_CONTACTS.getId());
            groupSendJob_son.setContent(groupSendJobParent.getContent());
            groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount((int)wxContactsPage.getTotal());
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(groupSendJobParent.getTimeInterval());
            groupSendJob_son.setBeginTime(groupSendJobParent.getBeginTime());
            groupSendJob_son.setEndTime(groupSendJobParent.getEndTime());
            groupSendJob_son.setExptime(groupSendJobParent.getExptime()); //当前时间之后的15天内
            groupSendJob_son.setUserLab(groupSendJobParent.getUserLab());
            groupSendJob_son.setUserRemark(groupSendJobParent.getUserRemark());
            groupSendJob_son.setNightTime(groupSendJobParent.getNightTime());
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try{
                //线程睡眠0.5秒
                Thread.sleep(500);
            } catch (Exception e){

            }

            //分页查询数据
            //延迟时间
            int delay = 0;//循环累加延迟时间
            while(wxContactsPage != null && wxContactsPage.getRecords() != null && wxContactsPage.getRecords().size() > 0){
                //发送消息
                for(EsWxContacts esWxContacts : wxContactsPage.getRecords()){
                    //发送MQ消息
                    GroupSendMsgDto groupSendMsgDto = new GroupSendMsgDto();
                    groupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                    groupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                    String msg = Tools.getStr(groupSendJob_son.getContent());
                    groupSendMsgDto.setMsg(msg.replace("[昵称]", esWxContacts.getNick()));
                    groupSendMsgDto.setMerId(esWxContacts.getMerId());
                    groupSendMsgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                    groupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                    groupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                    groupSendMsgDto.setUserId(null);
                    groupSendMsgDto.setBizUserId(esWxContacts.getWxid());
                    groupSendMsgDto.setNickName(esWxContacts.getNick());
                    groupSendMsgDto.setDelay(delay);
                    groupSendMsgDto.setOriginalDelay(delay);
                    delay = delay + groupSendJobParent.getTimeInterval(); //循环累加延迟时间
                    groupSendMsgDto.setRetry(0);
                    groupSendMsgDto.setLabel(groupSendJobParent.getUserLab());
                    String remark = Tools.getStr(groupSendJobParent.getUserRemark()).replace("[昵称]", esWxContacts.getNick());
                    groupSendMsgDto.setRemark(remark);
                    //群发消息
                    noticeMsgPushProducerService.groupSendMsg(groupSendMsgDto);
                }
                pageCurrent ++ ; //页面+1
                wxContactsQuery.setCurrent(pageCurrent); //修改页面
                wxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
            }
        }
    }

    /**
     * 批量注册
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxContactsQuery
     * @return null
     */
    @Async("taskExecutor")
    public void batchRegisterSync(WxContactsQuery wxContactsQuery){

        //查询机器人未到期
        int currentPage = 1; //当前页
        int size = 100;
        //查询总用户数
        wxContactsQuery.setSize(size);
        wxContactsQuery.setCurrent(currentPage);

        Page<WxContactsInfoVo> wxContactsInfoVoPage = findWxContactsList(wxContactsQuery, false);
        while(wxContactsInfoVoPage != null && wxContactsInfoVoPage.getRecords() != null && wxContactsInfoVoPage.getRecords().size() > 0){
            //发送消息
            for(WxContactsInfoVo wxContactsInfoVo : wxContactsInfoVoPage.getRecords()){
                try {
                    //会员信息
                    if(StringUtils.isNotBlank(wxContactsInfoVo.getWxid())){
                        User user = userService.findUserInfoByWxid(wxContactsInfoVo.getMerId(), wxContactsInfoVo.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
                        if(user == null){ //没有找到会员信息，才注册
                            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wxContactsInfoVo.getDeviceUniqueId(), wxContactsInfoVo.getMerId());
                            if(deviceWechatInfo != null){
                                //调用注册接口
                                WxContactsRegisterDto wxContactsRegisterDto = new WxContactsRegisterDto();
                                wxContactsRegisterDto.setMerId(wxContactsInfoVo.getMerId());
                                wxContactsRegisterDto.setDeviceId(wxContactsInfoVo.getDeviceId());
                                wxContactsRegisterDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                                wxContactsRegisterDto.setDeviceUniqueId(wxContactsInfoVo.getDeviceUniqueId());
                                wxContactsRegisterDto.setHeadImg(wxContactsInfoVo.getHimg());
                                wxContactsRegisterDto.setNickName(wxContactsInfoVo.getNick());
                                wxContactsRegisterDto.setWxid(wxContactsInfoVo.getWxid());
                                UzaiRespVo<Boolean> uzaiRespVo =  wxContactsFeignService.userreg2(wxContactsRegisterDto);
                                logger.info("---通讯录注册会员---wxContactsRegisterDto={}, uzaiRespVo={}",JSONObject.toJSONString(wxContactsRegisterDto), JSONObject.toJSONString(uzaiRespVo));
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error("通讯录注册会员失败，error={}", e.getMessage());
                }
            }

            currentPage ++ ; //页码+1
            wxContactsQuery.setCurrent(currentPage);
            wxContactsInfoVoPage = findWxContactsList(wxContactsQuery, false);
        }
    }

    /**
     * 查询微信通讯录总记录数
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxContactsQuery
     * @return null
     */
    public long searchTotal(WxContactsQuery wxContactsQuery){
        SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();


        boolQuery_and.must(QueryBuilders.termQuery("merId",wxContactsQuery.getMerId()));

        //好友类型(0-个人微信；1-微信群)
        if(wxContactsQuery.getUserType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("userType", wxContactsQuery.getUserType()));
        }

        //机器人唯一ID
        if(wxContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxContactsQuery.getDeviceUniqueIdList() != null && wxContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxContactsQuery.getDeviceUniqueIdList()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //微信昵称
        if(StringUtils.isNotBlank(wxContactsQuery.getNick())){
            boolQuery_or.should(QueryBuilders.matchQuery("nick", wxContactsQuery.getNick()));
            boolQuery_or.should(QueryBuilders.termQuery("nick.raw", wxContactsQuery.getNick()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxContactsQuery.getWxid()));
        }

        //微信号
        if(StringUtils.isNotBlank(wxContactsQuery.getWxno())){
            boolQuery_and.must(QueryBuilders.termQuery("wxno",wxContactsQuery.getWxno()));
        }

        //备注
        if(StringUtils.isNotBlank(wxContactsQuery.getRemark())){
            boolQuery_and.must(QueryBuilders.matchPhraseQuery("remark", wxContactsQuery.getRemark()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxContactsQuery.getBusyGroupSendMsgTime()));
        }

        //备注列表(匹配任何一个都算)
        List<String> remarkList = wxContactsQuery.getRemarkList();
        if(remarkList != null && remarkList.size() > 0){
            for (String remark : remarkList) {
                boolQuery_or.should(QueryBuilders.matchPhraseQuery("remark", remark));
            }
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));

        //查询
        //通过查询运营商其他索引分片获取分片索引
        String esName = EsIndexName.UZAI_WX_CONTACTS;
        String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxContactsQuery.getMerId());
        long total = elasticsearchUtilGroupMsg.searchTotal(mechantOtherEsIndexName, searchSourceBuilder);

        return total;
    }

    /**
     * 查询微信通讯录所有记录
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxContactsQuery
     * @return null
     */
    public List<WxContactsInfoVo> scrollSearchAll(WxContactsQuery wxContactsQuery){
        List<WxContactsInfoVo> wxContactsInfoVoList = new ArrayList<>();
        SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();


        boolQuery.must(QueryBuilders.termQuery("merId",wxContactsQuery.getMerId()));

        //好友类型(0-个人微信；1-微信群)
        if(wxContactsQuery.getUserType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("userType", wxContactsQuery.getUserType()));
        }

        //机器人唯一ID
        if(wxContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxContactsQuery.getDeviceUniqueIdList() != null && wxContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxContactsQuery.getDeviceUniqueIdList()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        //微信昵称
        if(StringUtils.isNotBlank(wxContactsQuery.getNick())){
            boolQuery_or.should(QueryBuilders.matchQuery("nick", wxContactsQuery.getNick()));
            boolQuery_or.should(QueryBuilders.termQuery("nick.raw", wxContactsQuery.getNick()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxContactsQuery.getWxid()));
        }

        //微信号
        if(StringUtils.isNotBlank(wxContactsQuery.getWxno())){
            boolQuery_and.must(QueryBuilders.termQuery("wxno",wxContactsQuery.getWxno()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxContactsQuery.getBusyGroupSendMsgTime()));
        }

        searchSourceBuilder.query(boolQuery_and.must(boolQuery_or));
        //查询
        //通过查询运营商其他索引分片获取分片索引
        String esName = EsIndexName.UZAI_WX_CONTACTS;
        String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, wxContactsQuery.getMerId());
        List<Map<String,Object>> dataList = elasticsearchUtilGroupMsg.scrollSearchAll(mechantOtherEsIndexName, searchSourceBuilder);
        if(dataList != null && dataList.size() > 0) {
            for (Map<String, Object> dataMp : dataList) {
                WxContactsInfoVo wxContactsInfoVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxContactsInfoVo.class);
                wxContactsInfoVoList.add(wxContactsInfoVo);
            }
        }
        return wxContactsInfoVoList;
    }

    /**
     * 根据单个机器人新建群发消息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param newBatchSendMessageTaskDto
     * @return null
     */
    public Integer newBatchSendMessageTaskSync(NewBatchSendMessageTaskDto newBatchSendMessageTaskDto, Long groupSendJobParentId, Long deviceUniqueId, String loginName){

        //记录发送消息总数
        int sendMsgTotal_real = 0;

        int now = DateUtil.getNowTime();

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueId, newBatchSendMessageTaskDto.getMerId());
        if(deviceWechatInfo == null){
            logger.error("--newBatchSendMessageTaskByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + deviceUniqueId);
            return sendMsgTotal_real;
        }

        WxContactsQuery wxContactsQuery = new WxContactsQuery();
        wxContactsQuery.setMerId(newBatchSendMessageTaskDto.getMerId());
        wxContactsQuery.setUserType(0); //个人微信通讯录
        wxContactsQuery.setDeviceUniqueId(deviceUniqueId);//单个机器人
        wxContactsQuery.setSubDeviceUniqueIdList(newBatchSendMessageTaskDto.getSubDeviceUniqueIdList());

        //免打扰时间
        Integer busyTimeInterval = newBatchSendMessageTaskDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = newBatchSendMessageTaskDto.getBeginTime() - busyTimeInterval * 3600 ;
            wxContactsQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总用户数
        int pageCurrent = 1; //从第一页开始查询
        wxContactsQuery.setCurrent(pageCurrent);
        wxContactsQuery.setSize(10); //群发消息，修改每页查询总数

        Page<EsWxContacts> wxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
        if(wxContactsPage != null && wxContactsPage.getRecords() != null && wxContactsPage.getRecords().size() > 0){
            //预计发送总数
            int sendTotal_will = (int)wxContactsPage.getTotal();
            //添加群发消息主任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(groupSendJobParentId); //主任务id
            groupSendJob_son.setMerId(newBatchSendMessageTaskDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wxContactsQuery.getDeviceUniqueId());
            String name = Tools.getStr(newBatchSendMessageTaskDto.getName());
            name = name.replace("[机器人昵称]", Tools.getStr(deviceWechatInfo.getDeviceName()))
                    .replace("[机器人备注]",Tools.getStr(deviceWechatInfo.getDeviceRemark()))
                    .replace("[创建时间]", Tools.getDateFormat(new Date(), "yyMMdd"))
                    .replace("[创建账号]", Tools.getStr(loginName));
            groupSendJob_son.setName(name);
            groupSendJob_son.setSource(GroupSendJobSourceEnum.PRIVATE_CONTACTS.getId());
            groupSendJob_son.setContent(newBatchSendMessageTaskDto.getContent());
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(0); //默认发送数为0
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeIntervalMin(newBatchSendMessageTaskDto.getTimeIntervalMin());
            groupSendJob_son.setTimeInterval(newBatchSendMessageTaskDto.getTimeInterval());
            groupSendJob_son.setBeginTime(newBatchSendMessageTaskDto.getBeginTime());
            groupSendJob_son.setEndTime(newBatchSendMessageTaskDto.getEndTime());
            groupSendJob_son.setExptime(now + 15*24*3600); //当前时间之后的15天内
            groupSendJob_son.setUserRemark(newBatchSendMessageTaskDto.getUserRemark());
            groupSendJob_son.setUserLab(Tools.getStrNull(JSONObject.toJSONString(newBatchSendMessageTaskDto.getUserLabList())));
            groupSendJob_son.setCleanLab(newBatchSendMessageTaskDto.getCleanLab());
            groupSendJob_son.setUserTags(Tools.getStrNull(JSONObject.toJSONString(newBatchSendMessageTaskDto.getUserTagsList())));
            groupSendJob_son.setNightTime(newBatchSendMessageTaskDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(newBatchSendMessageTaskDto.getBusyTimeInterval());
            groupSendJob_son.setIgnoreName(Tools.getStrEmpty(JSONObject.toJSONString(newBatchSendMessageTaskDto.getIgnoreNameList())));
            groupSendJob_son.setIgnoreRemark(Tools.getStrEmpty(JSONObject.toJSONString(newBatchSendMessageTaskDto.getIgnoreRemarkList())));
            groupSendJob_son.setSendStartTime(newBatchSendMessageTaskDto.getBeginTime());
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJob_son.setGroupSendType(newBatchSendMessageTaskDto.getGroupSendType());
            groupSendJob_son.setUserQueryPara(Tools.getStrNull(JSONObject.toJSONString(newBatchSendMessageTaskDto.getGroupSendJobUserQueryParaDto())));
            groupSendJob_son.setParaQueryType(Tools.getInteger(newBatchSendMessageTaskDto.getParaQueryType()));
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try {
                //是否有屏蔽昵称关键词
                boolean IgnoreNameListFlag = false;
                List<String> ignoreNameList = newBatchSendMessageTaskDto.getIgnoreNameList();
                if(ignoreNameList != null && ignoreNameList.size() > 0){
                    IgnoreNameListFlag = true;
                }

                //是否有屏蔽备注关键词
                boolean IgnoreRemarkListFlag = false;
                List<String> ignoreRemarkList = newBatchSendMessageTaskDto.getIgnoreRemarkList();
                if(ignoreRemarkList != null && ignoreRemarkList.size() > 0){
                    IgnoreRemarkListFlag = true;
                }

                //延迟时间
                int delay = 0;//循环累加延迟时间

                //判断群发助手
                int groupSendType = newBatchSendMessageTaskDto.getGroupSendType();
                if(groupSendType == 0){//普通发送
                    while(wxContactsPage != null && wxContactsPage.getRecords() != null && wxContactsPage.getRecords().size() > 0) {
                        //临时封装发送消息对象列表
                        List<NewGroupSendMsgDto> newGroupSendMsgDtoList = new ArrayList<>();
                        List<EsWxContacts> esWxContactsList = wxContactsPage.getRecords();
                        if(esWxContactsList != null && esWxContactsList.size() > 0){
                            //判断是否先需要匹配查询条件(1-发送前先筛选条件后创建任务)
                            if(Tools.getInteger(newBatchSendMessageTaskDto.getParaQueryType()).intValue() == 1){
                                //条件查询过滤，返回符合条件的通讯录
                                esWxContactsList = checkParaQuery(esWxContactsList, newBatchSendMessageTaskDto);
                            }
                            for (EsWxContacts esWxContacts : esWxContactsList) {
                                //是否需要发送消息, 默认发送
                                boolean sendMsgFlag = true;

                                if(IgnoreNameListFlag) {//需要过滤昵称
                                    String nick = Tools.getStr(esWxContacts.getNick());
                                    for(String ignoreName : ignoreNameList) {
                                        if(nick.contains(ignoreName)){
                                            //匹配到了过滤昵称标签，则不发送消息
                                            sendMsgFlag = false;
                                            break;
                                        }
                                    }
                                }

                                //如果昵称没有成功匹配过滤，则再匹配备注过滤，如果昵称已经匹配过滤成功了，则无需再匹配备注
                                if(sendMsgFlag){
                                    if(IgnoreRemarkListFlag) {//需要过滤备注
                                        String remark = Tools.getStr(esWxContacts.getRemark());
                                        for(String ignoreRemark : ignoreRemarkList) {
                                            if(remark.contains(ignoreRemark)){
                                                //匹配到了过滤备注标签，则不发送消息
                                                sendMsgFlag = false;
                                                break;
                                            }
                                        }
                                    }
                                }

                                //没有过滤则发送消息
                                if(sendMsgFlag){
                                    //调用微服务群发消息
                                    NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                                    newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                                    newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                                    String msg = Tools.getStr(groupSendJob_son.getContent());
                                    msg = msg.replace("[随机表情]",Tools.getStr(EmojiUtil.getRandomEmoji()))
                                            .replace("[昵称]",Tools.getStr(esWxContacts.getNick()));
                                    newGroupSendMsgDto.setMsg(msg);
                                    //群发助手
                                    newGroupSendMsgDto.setGroupSendType(newBatchSendMessageTaskDto.getGroupSendType());
                                    newGroupSendMsgDto.setMerId(esWxContacts.getMerId());
                                    newGroupSendMsgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                                    newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                                    newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                                    newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                                    newGroupSendMsgDto.setUserId(null);
                                    newGroupSendMsgDto.setBizUserId(esWxContacts.getWxid());
                                    newGroupSendMsgDto.setNickName(esWxContacts.getNick());
                                    newGroupSendMsgDto.setDelay(delay);
                                    newGroupSendMsgDto.setOriginalDelay(delay);
                                    //循环累加延迟时间(从最小和最大之间随机获取间隔时间)
                                    //发送间隔最小时间
                                    Integer rateMin = Tools.getInteger(newBatchSendMessageTaskDto.getTimeIntervalMin());
                                    //发送间隔最大时间
                                    Integer rateMax = Tools.getInteger(newBatchSendMessageTaskDto.getTimeInterval());
                                    int random = (int)(Math.random()*(rateMax-rateMin+1)+rateMin);
                                    delay = delay + random;
                                    newGroupSendMsgDto.setRetry(0);
                                    newGroupSendMsgDto.setLabel(Tools.getStrNull(JSONObject.toJSONString(newBatchSendMessageTaskDto.getUserLabList())));
                                    //会员标签
                                    newGroupSendMsgDto.setUserTags(Tools.getStrNull(JSONObject.toJSONString(newBatchSendMessageTaskDto.getUserTagsList())));
                                    String userRemark = Tools.getStr(newBatchSendMessageTaskDto.getUserRemark());
                                    userRemark = userRemark.replace("[昵称]",Tools.getStr(esWxContacts.getNick()))
                                            .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                                    newGroupSendMsgDto.setRemark(userRemark);
                                    newGroupSendMsgDtoList.add(newGroupSendMsgDto);
                                }
                            }
                        }

                        //调用微服务批量发送消息
                        if(newGroupSendMsgDtoList.size() > 0){
                            UzaiRespVo<Boolean>  uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                            if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                                //实际发送总数累加
                                sendMsgTotal_real = sendMsgTotal_real + newGroupSendMsgDtoList.size();
                                //logger.info("----通讯录新建群发消息任务---para={}, size={}. result={}", JSONObject.toJSONString(newGroupSendMsgDtoList), newGroupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                            }else{
                                logger.error("----通讯录新建群发消息调用接口--subId={}, uzaiRespVo={}", groupSendJob_son.getId(),  JSONObject.toJSONString(uzaiRespVo));
                                //失败的在调用一次,再次失败则修改群发消息条数
                                UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                                if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                    sendMsgTotal_real = sendMsgTotal_real + newGroupSendMsgDtoList.size();
                                }else{
                                    logger.error("----通讯录新建群发消息调用接口--subId={}, uzaiRespVo={}", groupSendJob_son.getId(),  JSONObject.toJSONString(uzaiRespVo_repeat));
                                }
                            }
                        }

                        pageCurrent ++ ; //页面+1
                        wxContactsQuery.setCurrent(pageCurrent); //修改页面
                        wxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
                    }
                }else if(groupSendType == 1){//群发助手发发送

                    //群发助手封装的会员对象信息列表
                    List<NewGroupSendMsgDto.GroupSendUserInfo> groupSendUserInfoList = new ArrayList<>();

                    while(wxContactsPage != null && wxContactsPage.getRecords() != null && wxContactsPage.getRecords().size() > 0) {
                        List<EsWxContacts> esWxContactsList = wxContactsPage.getRecords();
                        if(esWxContactsList != null && esWxContactsList.size() > 0){
                            //判断是否先需要匹配查询条件(1-发送前先筛选条件后创建任务)
                            if(Tools.getInteger(newBatchSendMessageTaskDto.getParaQueryType()).intValue() == 1){
                                //条件查询过滤，返回符合条件的通讯录
                                esWxContactsList = checkParaQuery(esWxContactsList, newBatchSendMessageTaskDto);
                            }
                            for (EsWxContacts esWxContacts : esWxContactsList) {
                                //是否需要发送消息, 默认发送
                                boolean sendMsgFlag = true;

                                if(IgnoreNameListFlag) {//需要过滤昵称
                                    String nick = Tools.getStr(esWxContacts.getNick());
                                    for(String ignoreName : ignoreNameList) {
                                        if(nick.contains(ignoreName)){
                                            //匹配到了过滤昵称标签，则不发送消息
                                            sendMsgFlag = false;
                                            break;
                                        }
                                    }
                                }

                                //如果昵称没有成功匹配过滤，则再匹配备注过滤，如果昵称已经匹配过滤成功了，则无需再匹配备注
                                if(sendMsgFlag){
                                    if(IgnoreRemarkListFlag) {//需要过滤备注
                                        String remark = Tools.getStr(esWxContacts.getRemark());
                                        for(String ignoreRemark : ignoreRemarkList) {
                                            if(remark.contains(ignoreRemark)){
                                                //匹配到了过滤备注标签，则不发送消息
                                                sendMsgFlag = false;
                                                break;
                                            }
                                        }
                                    }
                                }

                                //没有过滤则发送消息
                                if(sendMsgFlag){
                                    NewGroupSendMsgDto.GroupSendUserInfo groupSendUserInfo = new NewGroupSendMsgDto.GroupSendUserInfo();
                                    groupSendUserInfo.setUserId(null);
                                    groupSendUserInfo.setBizUserId(esWxContacts.getWxid());
                                    groupSendUserInfo.setNickName(esWxContacts.getNick());
                                    groupSendUserInfoList.add(groupSendUserInfo);
                                }

                                //判断发送的通讯录格式是否为200，等于200就打包发送一次消息
                                if(groupSendUserInfoList != null && groupSendUserInfoList.size() == Const.WxContactsGroupSend.GROUPSENDMSG_PACKAGE_NUM){
                                    //调用微服务群发消息
                                    NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                                    newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                                    newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                                    String msg = Tools.getStr(groupSendJob_son.getContent());
                                    newGroupSendMsgDto.setMsg(groupSendJob_son.getContent());
                                    newGroupSendMsgDto.setMerId(newBatchSendMessageTaskDto.getMerId());
                                    newGroupSendMsgDto.setDeviceUniqueId(deviceUniqueId);
                                    newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                                    newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                                    newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                                    newGroupSendMsgDto.setBizUserId(IdWorker.getIdStr());
                                    newGroupSendMsgDto.setDelay(delay);
                                    newGroupSendMsgDto.setOriginalDelay(delay);
                                    //delay = delay + Const.WxContactsGroupSend.GROUPSENDMSG_DELAY; //循环累加延迟时间30分钟
                                    //循环累加延迟时间(从最小和最大之间随机获取间隔时间)
                                    //发送间隔最小时间
                                    Integer rateMin = Tools.getInteger(newBatchSendMessageTaskDto.getTimeIntervalMin());
                                    //发送间隔最大时间
                                    Integer rateMax = Tools.getInteger(newBatchSendMessageTaskDto.getTimeInterval());
                                    int random = (int)(Math.random()*(rateMax-rateMin+1)+rateMin);
                                    delay = delay + random;
                                    newGroupSendMsgDto.setRetry(0);
                                    newGroupSendMsgDto.setLabel(null);
                                    newGroupSendMsgDto.setRemark(newBatchSendMessageTaskDto.getUserRemark());
                                    //群发助手
                                    newGroupSendMsgDto.setGroupSendType(newBatchSendMessageTaskDto.getGroupSendType());
                                    //封装群发会员列表
                                    newGroupSendMsgDto.setGroupSendUserInfos(groupSendUserInfoList);
                                    //临时封装发送消息对象列表
                                    List<NewGroupSendMsgDto> newGroupSendMsgDtoList = new ArrayList<>();
                                    newGroupSendMsgDtoList.add(newGroupSendMsgDto);
                                    //调用微服务批量发送消息
                                    UzaiRespVo<Boolean>  uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                                    if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                                        //实际发送总数累加
                                        sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                                        //清空封装的会员列表
                                        groupSendUserInfoList.clear();
                                        //logger.info("----通讯录新建群发消息任务---para={}, size={}. result={}", JSONObject.toJSONString(newGroupSendMsgDtoList), newGroupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                                    }else{
                                        logger.error("----通讯录新建群发消息任务失败---size={}", newGroupSendMsgDtoList.size());
                                        //失败的在调用一次,再次失败则修改群发消息条数
                                        UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                                        if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                            sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                                            //清空封装的会员列表
                                            groupSendUserInfoList.clear();
                                        }else{
                                            //最后也会清空封装的会员列表
                                            groupSendUserInfoList.clear();
                                        }
                                    }
                                }
                            }
                        }

                        pageCurrent ++ ; //页面+1
                        wxContactsQuery.setCurrent(pageCurrent); //修改页面
                        wxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
                    }

                    //最后再发送未满200个助手
                    if(groupSendUserInfoList != null && groupSendUserInfoList.size() > 0){
                        //调用微服务群发消息
                        NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                        newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                        newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                        String msg = Tools.getStr(groupSendJob_son.getContent());
                        newGroupSendMsgDto.setMsg(groupSendJob_son.getContent());
                        newGroupSendMsgDto.setMerId(newBatchSendMessageTaskDto.getMerId());
                        newGroupSendMsgDto.setDeviceUniqueId(deviceUniqueId);
                        newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                        newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                        newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                        newGroupSendMsgDto.setBizUserId(IdWorker.getIdStr());
                        newGroupSendMsgDto.setDelay(delay);
                        newGroupSendMsgDto.setOriginalDelay(delay);
                        newGroupSendMsgDto.setRetry(0);
                        newGroupSendMsgDto.setLabel(null);
                        newGroupSendMsgDto.setRemark(newBatchSendMessageTaskDto.getUserRemark());
                        //群发助手
                        newGroupSendMsgDto.setGroupSendType(newBatchSendMessageTaskDto.getGroupSendType());
                        //封装群发会员列表
                        newGroupSendMsgDto.setGroupSendUserInfos(groupSendUserInfoList);
                        //临时封装发送消息对象列表
                        List<NewGroupSendMsgDto> newGroupSendMsgDtoList = new ArrayList<>();
                        newGroupSendMsgDtoList.add(newGroupSendMsgDto);
                        //调用微服务批量发送消息
                        UzaiRespVo<Boolean>  uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                            //实际发送总数累加
                            sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                            //清空封装的会员列表
                            groupSendUserInfoList.clear();
                            //logger.info("----通讯录新建群发消息任务---para={}, size={}. result={}", JSONObject.toJSONString(newGroupSendMsgDtoList), newGroupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                        }else{
                            logger.error("----通讯录新建群发消息任务失败---size={}", newGroupSendMsgDtoList.size());
                            //失败的在调用一次,再次失败则修改群发消息条数
                            UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                            if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                //实际发送总数累加
                                sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                                //清空封装的会员列表
                                groupSendUserInfoList.clear();
                            }else{
                                //最后也会清空封装的会员列表
                                groupSendUserInfoList.clear();
                            }
                        }
                    }
                }
            }catch (Exception e){
                logger.error("---通讯录群发消息异常---deviceUniqueId={},msg={}", deviceUniqueId, e.getMessage());
            }

            //修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(sendMsgTotal_real);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval() != null ? groupSendJob_son.getTimeInterval() : 1800); //如果此任务的间隔时间为空，则默认设置为半个小时
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }

        return sendMsgTotal_real;
    }

    /**
     * 查询根据单个机器人新建群发消息总数
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param newBatchSendMessageTaskDto
     * @return null
     */
    public int findBatchSendMessageTaskSyncCount(NewBatchSendMessageTaskDto newBatchSendMessageTaskDto, Long deviceUniqueId){

        //记录发送消息总数
        int sendMsgTotal_real = 0;

        WxContactsQuery wxContactsQuery = new WxContactsQuery();
        wxContactsQuery.setMerId(newBatchSendMessageTaskDto.getMerId());
        wxContactsQuery.setUserType(0); //个人微信通讯录
        wxContactsQuery.setDeviceUniqueId(deviceUniqueId);//单个机器人
        wxContactsQuery.setSubDeviceUniqueIdList(newBatchSendMessageTaskDto.getSubDeviceUniqueIdList());
        //免打扰时间
        Integer busyTimeInterval = newBatchSendMessageTaskDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是小时)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = newBatchSendMessageTaskDto.getBeginTime() - busyTimeInterval * 3600 ;
            wxContactsQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //是否有屏蔽昵称关键词
        boolean IgnoreNameListFlag = false;
        List<String> ignoreNameList = newBatchSendMessageTaskDto.getIgnoreNameList();
        if(ignoreNameList != null && ignoreNameList.size() > 0){
            IgnoreNameListFlag = true;
        }

        //是否有屏蔽备注关键词
        boolean IgnoreRemarkListFlag = false;
        List<String> ignoreRemarkList = newBatchSendMessageTaskDto.getIgnoreRemarkList();
        if(ignoreRemarkList != null && ignoreRemarkList.size() > 0){
            IgnoreRemarkListFlag = true;
        }

        //查询总用户数
        int pageCurrent = 1; //从第一页开始查询
        wxContactsQuery.setCurrent(pageCurrent);
        wxContactsQuery.setSize(10);

        Page<EsWxContacts> wxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
        if(wxContactsPage != null && wxContactsPage.getRecords() != null && wxContactsPage.getRecords().size() > 0){
            try {
                while(wxContactsPage != null && wxContactsPage.getRecords() != null && wxContactsPage.getRecords().size() > 0) {
                    List<EsWxContacts> esWxContactsList = wxContactsPage.getRecords();
                    if(esWxContactsList != null && esWxContactsList.size() > 0){
                        //判断是否先需要匹配查询条件(1-发送前先筛选条件后创建任务)
                        if(Tools.getInteger(newBatchSendMessageTaskDto.getParaQueryType()).intValue() == 1){
                            //条件查询过滤，返回符合条件的通讯录
                            esWxContactsList = checkParaQuery(esWxContactsList, newBatchSendMessageTaskDto);
                        }

                        for (EsWxContacts esWxContacts : esWxContactsList) {
                            //是否需要发送消息, 默认发送
                            boolean sendMsgFlag = true;

                            if(IgnoreNameListFlag) {//需要过滤昵称
                                String nick = Tools.getStr(esWxContacts.getNick());
                                for(String ignoreName : ignoreNameList) {
                                    if(nick.contains(ignoreName)){
                                        //匹配到了过滤昵称标签，则不发送消息
                                        sendMsgFlag = false;
                                        break;
                                    }
                                }
                            }

                            //如果昵称没有成功匹配过滤，则再匹配备注过滤，如果昵称已经匹配过滤成功了，则无需再匹配备注
                            if(sendMsgFlag){
                                if(IgnoreRemarkListFlag) {//需要过滤备注
                                    String remark = Tools.getStr(esWxContacts.getRemark());
                                    for(String ignoreRemark : ignoreRemarkList) {
                                        if(remark.contains(ignoreRemark)){
                                            //匹配到了过滤备注标签，则不发送消息
                                            sendMsgFlag = false;
                                            break;
                                        }
                                    }
                                }
                            }
                            if(sendMsgFlag){
                                sendMsgTotal_real++;
                            }
                        }
                    }
                    //调用微服务批量发送消息
                    pageCurrent ++ ; //页面+1
                    wxContactsQuery.setCurrent(pageCurrent); //修改页面
                    wxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
                }
            }catch (Exception e){
                logger.error("---通讯录群发消息异常---deviceUniqueId={},msg={}", deviceUniqueId, e.getMessage());
            }
        }

        return sendMsgTotal_real;
    }


    //群发时，判断符合条件的会员列表，符合条件的返回
    private List<EsWxContacts> checkParaQuery(List<EsWxContacts> esWxContactsList, NewBatchSendMessageTaskDto newBatchSendMessageTaskDto){

        //存放符合条件的通讯录
        List<EsWxContacts> esWxContactsList_volid = new ArrayList<>();

        if(esWxContactsList == null ){
            return esWxContactsList_volid;
        }

        //存放当前页通讯录里查询出的微信id列表
        List<String> wxidList_query = new ArrayList<>();
        for (EsWxContacts esWxContacts : esWxContactsList) {
            wxidList_query.add(esWxContacts.getWxid());
        }

        //获取群发查询条件
        GroupSendJobUserQueryParaDto groupSendJobUserQueryParaDto = newBatchSendMessageTaskDto.getGroupSendJobUserQueryParaDto();
        //判断是否有查询条件，如果没有，则不需要查询
        if(groupSendJobUserQueryParaDto != null){
            //1-先验证订单查询条件
            if(!groupSendJobUserQueryParaDto.checkOrderConditionIsAllNull()){
                GroupSendJobConditionOrderDto conditionOrder = new GroupSendJobConditionOrderDto();
                conditionOrder.setCidList(groupSendJobUserQueryParaDto.getCidList());
                conditionOrder.setOrderCreateTimeStart(groupSendJobUserQueryParaDto.getOrderCreateTimeStart());
                conditionOrder.setOrderCreateTimeEnd(groupSendJobUserQueryParaDto.getOrderCreateTimeEnd());
                conditionOrder.setOrderTitleList(groupSendJobUserQueryParaDto.getOrderTitleList());
                conditionOrder.setPlatform(groupSendJobUserQueryParaDto.getPlatform());
                conditionOrder.setBizUserIdList(wxidList_query);
                conditionOrder.setMerId(newBatchSendMessageTaskDto.getMerId());
                wxidList_query = groupSendJobConditionService.checkOrderConditionWithUserIds(conditionOrder);
                //判断是否匹配到符合订单条件的会员，如果未查询到，则返回null
                if(wxidList_query == null || wxidList_query.size() == 0){
                    return esWxContactsList_volid;
                }
            }

            //2-再验证会员查询条件
            if(!groupSendJobUserQueryParaDto.checkUserConditionIsAllNull()){
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                wechatUserQuery.setRegChannelList(groupSendJobUserQueryParaDto.getRegChannelList());
                wechatUserQuery.setRegTimeStart(groupSendJobUserQueryParaDto.getRegTimeStart());
                wechatUserQuery.setRegTimeEnd(groupSendJobUserQueryParaDto.getRegTimeEnd());
                wechatUserQuery.setTbLastOrderNo(groupSendJobUserQueryParaDto.getTbLastOrderNo());
                wechatUserQuery.setLastOrderTimeStart(groupSendJobUserQueryParaDto.getLastOrderTimeStart());
                wechatUserQuery.setLastOrderTimeEnd(groupSendJobUserQueryParaDto.getLastOrderTimeEnd());
                wechatUserQuery.setLastOrderType(groupSendJobUserQueryParaDto.getLastOrderType());
                wechatUserQuery.setLastOrderTypeTime(groupSendJobUserQueryParaDto.getLastOrderTypeTime());
                wechatUserQuery.setUserTypeList(groupSendJobUserQueryParaDto.getUserTypeList());
                wechatUserQuery.setGender(groupSendJobUserQueryParaDto.getGender());
                wechatUserQuery.setRemarkList(groupSendJobUserQueryParaDto.getRemarkList());
                wechatUserQuery.setRemarkNullFlag(groupSendJobUserQueryParaDto.getRemarkNullFlag());
                wechatUserQuery.setRemarkExcludeList(groupSendJobUserQueryParaDto.getRemarkExcludeList());
                wechatUserQuery.setNameList(groupSendJobUserQueryParaDto.getNameList());
                wechatUserQuery.setNameNullFlag(groupSendJobUserQueryParaDto.getNameNullFlag());
                wechatUserQuery.setNameExcludeList(groupSendJobUserQueryParaDto.getNameExcludeList());
                wechatUserQuery.setTagsList(groupSendJobUserQueryParaDto.getTagsList());
                wechatUserQuery.setTagsNullFlag(groupSendJobUserQueryParaDto.getTagsNullFlag());
                wechatUserQuery.setTagsExcludeList(groupSendJobUserQueryParaDto.getTagsExcludeList());
                wechatUserQuery.setSysTagsList(groupSendJobUserQueryParaDto.getSysTagsList());
                wechatUserQuery.setSysTagsNullFlag(groupSendJobUserQueryParaDto.getSysTagsNullFlag());
                wechatUserQuery.setSysTagsExcludeList(groupSendJobUserQueryParaDto.getSysTagsExcludeList());
                wechatUserQuery.setMinBalance(groupSendJobUserQueryParaDto.getMinBalance());
                wechatUserQuery.setMaxBalance(groupSendJobUserQueryParaDto.getMaxBalance());
                wechatUserQuery.setMinIntegral(groupSendJobUserQueryParaDto.getMinIntegral());
                wechatUserQuery.setMaxIntegral(groupSendJobUserQueryParaDto.getMaxIntegral());
                wechatUserQuery.setMerId(newBatchSendMessageTaskDto.getMerId());
                wechatUserQuery.setWxidList(wxidList_query);
                List<WechatUser> wechatUserList = wechatUserMapper.findByList(wechatUserQuery);
                //未找到符合条件会员，则返回空
                if(wechatUserList == null || wechatUserList.size() == 0){
                    return esWxContactsList_volid;
                }

                //找到了符合条件的微信wxid，找出来封装成列表返回
                wxidList_query = wechatUserList.stream().map(WechatUser::getWxid).collect(Collectors.toList());
            }

            //循环查询符合条件的通讯录
            for (String wxid : wxidList_query) {
                for (EsWxContacts esWxContacts : esWxContactsList) {
                    if(wxid.equals(esWxContacts.getWxid())){
                        esWxContactsList_volid.add(esWxContacts);
                        break;
                    }
                }
            }
        }
        return esWxContactsList_volid;
    }

    /**
     * 修复根据单个机器人新建群发消息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param groupSendJobChild
     * @return null
     */
    public void repairBatchSendMessageTaskSync(GroupSendJob groupSendJobChild){
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(groupSendJobChild.getDeviceUniqueId(), groupSendJobChild.getMerId());
        if(deviceWechatInfo == null){
            logger.error("--newBatchSendMessageTaskByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + groupSendJobChild.getDeviceUniqueId());
            return;
        }

        WxContactsQuery wxContactsQuery = new WxContactsQuery();
        wxContactsQuery.setMerId(groupSendJobChild.getMerId());
        wxContactsQuery.setUserType(0); //个人微信通讯录
        wxContactsQuery.setDeviceUniqueId(groupSendJobChild.getDeviceUniqueId());//单个机器人

        //免打扰时间
        Integer busyTimeInterval = groupSendJobChild.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = groupSendJobChild.getBeginTime() - busyTimeInterval * 3600 ;
            wxContactsQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询总用户数
        int pageCurrent = 1; //从第一页开始查询
        wxContactsQuery.setCurrent(pageCurrent);
        wxContactsQuery.setSize(10);

        Page<EsWxContacts> esWxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
        if(esWxContactsPage != null && esWxContactsPage.getRecords() != null && esWxContactsPage.getRecords().size() > 0){
            //添加群发消息子任务
            Integer now = DateUtil.getNowTime();

            //是否有屏蔽昵称关键词
            boolean IgnoreNameListFlag = false;
            List<String> ignoreNameList = JSONObject.parseArray(groupSendJobChild.getIgnoreName(), String.class);
            if(ignoreNameList != null && ignoreNameList.size() > 0){
                IgnoreNameListFlag = true;
            }

            //是否有屏蔽备注关键词
            boolean IgnoreRemarkListFlag = false;
            List<String> ignoreRemarkList = JSONObject.parseArray(groupSendJobChild.getIgnoreRemark(), String.class);
            if(ignoreRemarkList != null && ignoreRemarkList.size() > 0){
                IgnoreRemarkListFlag = true;
            }

            //记录发送消息总数
            int sendMsgTotal_real = 0;

            //延迟时间
            int delay = 0;//循环累加延迟时间

            //判断群发助手
            int groupSendType = groupSendJobChild.getGroupSendType();
            if(groupSendType == 0){//普通发送
                while(esWxContactsPage != null && esWxContactsPage.getRecords() != null && esWxContactsPage.getRecords().size() > 0) {
                    //临时封装发送消息对象列表
                    List<NewGroupSendMsgDto> newGroupSendMsgDtoList = new ArrayList<>();
                    List<EsWxContacts> esWxContactsList = esWxContactsPage.getRecords();
                    for (EsWxContacts esWxContacts : esWxContactsList) {

                        //是否需要发送消息, 默认发送
                        boolean sendMsgFlag = true;

                        if(IgnoreNameListFlag) {//需要过滤昵称
                            String nick = Tools.getStr(esWxContacts.getNick());
                            for(String ignoreName : ignoreNameList) {
                                if(nick.contains(ignoreName)){
                                    //匹配到了过滤昵称标签，则不发送消息
                                    sendMsgFlag = false;
                                    break;
                                }
                            }
                        }

                        //如果昵称没有成功匹配过滤，则再匹配备注过滤，如果昵称已经匹配过滤成功了，则无需再匹配备注
                        if(sendMsgFlag){
                            if(IgnoreRemarkListFlag) {//需要过滤备注
                                String remark = Tools.getStr(esWxContacts.getRemark());
                                for(String ignoreRemark : ignoreRemarkList) {
                                    if(remark.contains(ignoreRemark)){
                                        //匹配到了过滤备注标签，则不发送消息
                                        sendMsgFlag = false;
                                        break;
                                    }
                                }
                            }
                        }

                        //没有过滤则发送消息
                        if(sendMsgFlag){
                            //调用微服务群发消息
                            NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                            newGroupSendMsgDto.setParentJobId(groupSendJobChild.getParentId());
                            newGroupSendMsgDto.setChildJobId(groupSendJobChild.getId());
                            String msg = Tools.getStr(groupSendJobChild.getContent());
                            msg = msg.replace("[随机表情]",Tools.getStr(EmojiUtil.getRandomEmoji()))
                                    .replace("[昵称]",Tools.getStr(esWxContacts.getNick()));
                            newGroupSendMsgDto.setMsg(msg);
                            //群发助手
                            newGroupSendMsgDto.setGroupSendType(groupSendJobChild.getGroupSendType());
                            newGroupSendMsgDto.setMerId(esWxContacts.getMerId());
                            newGroupSendMsgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                            newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                            newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                            newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                            newGroupSendMsgDto.setUserId(null);
                            newGroupSendMsgDto.setBizUserId(esWxContacts.getWxid());
                            newGroupSendMsgDto.setNickName(esWxContacts.getNick());
                            newGroupSendMsgDto.setDelay(delay);
                            newGroupSendMsgDto.setOriginalDelay(delay);
                            delay = delay + groupSendJobChild.getTimeInterval(); //循环累加延迟时间
                            newGroupSendMsgDto.setRetry(0);
                            newGroupSendMsgDto.setLabel(groupSendJobChild.getUserLab());
                            String userRemark = Tools.getStr(groupSendJobChild.getUserRemark());
                            userRemark = userRemark.replace("[昵称]",Tools.getStr(esWxContacts.getNick()))
                                    .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                            newGroupSendMsgDto.setRemark(userRemark);
                            newGroupSendMsgDtoList.add(newGroupSendMsgDto);
                        }
                    }

                    //调用微服务批量发送消息
                    if(newGroupSendMsgDtoList.size() > 0){
                        UzaiRespVo<Boolean>  uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                            //实际发送总数累加
                            sendMsgTotal_real = sendMsgTotal_real + newGroupSendMsgDtoList.size();
                            //logger.info("----通讯录新建群发消息任务---para={}, size={}. result={}", JSONObject.toJSONString(wxContactsQuery), newGroupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                        }else{
                            logger.error("----通讯录新建群发消息任务失败---size={}", newGroupSendMsgDtoList.size());
                            //失败的在调用一次,再次失败则修改群发消息条数
                            UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                            if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                sendMsgTotal_real = sendMsgTotal_real + newGroupSendMsgDtoList.size();
                            }
                        }
                    }

                    pageCurrent ++ ; //页面+1
                    wxContactsQuery.setCurrent(pageCurrent); //修改页面
                    esWxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
                }
            }else if(groupSendType == 1){//群发助手发发送

                //群发助手封装的会员对象信息列表
                List<NewGroupSendMsgDto.GroupSendUserInfo> groupSendUserInfoList = new ArrayList<>();

                while(esWxContactsPage != null && esWxContactsPage.getRecords() != null && esWxContactsPage.getRecords().size() > 0) {
                    List<EsWxContacts> esWxContactsList = esWxContactsPage.getRecords();
                    for (EsWxContacts esWxContacts : esWxContactsList) {
                        //是否需要发送消息, 默认发送
                        boolean sendMsgFlag = true;

                        if(IgnoreNameListFlag) {//需要过滤昵称
                            String nick = Tools.getStr(esWxContacts.getNick());
                            for(String ignoreName : ignoreNameList) {
                                if(nick.contains(ignoreName)){
                                    //匹配到了过滤昵称标签，则不发送消息
                                    sendMsgFlag = false;
                                    break;
                                }
                            }
                        }

                        //如果昵称没有成功匹配过滤，则再匹配备注过滤，如果昵称已经匹配过滤成功了，则无需再匹配备注
                        if(sendMsgFlag){
                            if(IgnoreRemarkListFlag) {//需要过滤备注
                                String remark = Tools.getStr(esWxContacts.getRemark());
                                for(String ignoreRemark : ignoreRemarkList) {
                                    if(remark.contains(ignoreRemark)){
                                        //匹配到了过滤备注标签，则不发送消息
                                        sendMsgFlag = false;
                                        break;
                                    }
                                }
                            }
                        }

                        //没有过滤则发送消息
                        if(sendMsgFlag){
                            NewGroupSendMsgDto.GroupSendUserInfo groupSendUserInfo = new NewGroupSendMsgDto.GroupSendUserInfo();
                            groupSendUserInfo.setUserId(null);
                            groupSendUserInfo.setBizUserId(esWxContacts.getWxid());
                            groupSendUserInfo.setNickName(esWxContacts.getNick());
                            groupSendUserInfoList.add(groupSendUserInfo);
                        }

                        //判断发送的通讯录格式是否为200，等于200就打包发送一次消息
                        if(groupSendUserInfoList != null && groupSendUserInfoList.size() == Const.WxContactsGroupSend.GROUPSENDMSG_PACKAGE_NUM){
                            //调用微服务群发消息
                            NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                            newGroupSendMsgDto.setParentJobId(groupSendJobChild.getParentId());
                            newGroupSendMsgDto.setChildJobId(groupSendJobChild.getId());
                            String msg = Tools.getStr(groupSendJobChild.getContent());
                            newGroupSendMsgDto.setMsg(groupSendJobChild.getContent());
                            newGroupSendMsgDto.setMerId(groupSendJobChild.getMerId());
                            newGroupSendMsgDto.setDeviceUniqueId(groupSendJobChild.getDeviceUniqueId());
                            newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                            newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                            newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                            newGroupSendMsgDto.setBizUserId(IdWorker.getIdStr());
                            newGroupSendMsgDto.setDelay(delay);
                            newGroupSendMsgDto.setOriginalDelay(delay);
                            delay = delay + Const.WxContactsGroupSend.GROUPSENDMSG_DELAY; //循环累加延迟时间30分钟
                            newGroupSendMsgDto.setRetry(0);
                            newGroupSendMsgDto.setLabel(groupSendJobChild.getUserLab());
                            newGroupSendMsgDto.setRemark(groupSendJobChild.getUserRemark());
                            //群发助手
                            newGroupSendMsgDto.setGroupSendType(groupSendJobChild.getGroupSendType());
                            //封装群发会员列表
                            newGroupSendMsgDto.setGroupSendUserInfos(groupSendUserInfoList);
                            //临时封装发送消息对象列表
                            List<NewGroupSendMsgDto> newGroupSendMsgDtoList = new ArrayList<>();
                            newGroupSendMsgDtoList.add(newGroupSendMsgDto);
                            //调用微服务批量发送消息
                            UzaiRespVo<Boolean>  uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                            if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                                //实际发送总数累加
                                sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                                //清空封装的会员列表
                                groupSendUserInfoList.clear();
                                //logger.info("----通讯录新建群发消息任务---para={}, size={}. result={}", JSONObject.toJSONString(wxContactsQuery), newGroupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                            }else{
                                logger.error("----通讯录新建群发消息任务失败---size={}", newGroupSendMsgDtoList.size());
                                //失败的在调用一次,再次失败则修改群发消息条数
                                UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                                if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                    sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                                    //清空封装的会员列表
                                    groupSendUserInfoList.clear();
                                }else{
                                    //最后也会清空封装的会员列表
                                    groupSendUserInfoList.clear();
                                }
                            }
                        }
                    }
                    pageCurrent ++ ; //页面+1
                    wxContactsQuery.setCurrent(pageCurrent); //修改页面
                    esWxContactsPage = findWxContactsListForGroupSendMsg(wxContactsQuery);
                }

                //最后再发送未满200个助手
                if(groupSendUserInfoList != null && groupSendUserInfoList.size() > 0){
                    //调用微服务群发消息
                    NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                    newGroupSendMsgDto.setParentJobId(groupSendJobChild.getParentId());
                    newGroupSendMsgDto.setChildJobId(groupSendJobChild.getId());
                    String msg = Tools.getStr(groupSendJobChild.getContent());
                    newGroupSendMsgDto.setMsg(groupSendJobChild.getContent());
                    newGroupSendMsgDto.setMerId(groupSendJobChild.getMerId());
                    newGroupSendMsgDto.setDeviceUniqueId(groupSendJobChild.getDeviceUniqueId());
                    newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                    newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                    newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                    newGroupSendMsgDto.setBizUserId(IdWorker.getIdStr());
                    newGroupSendMsgDto.setDelay(delay);
                    newGroupSendMsgDto.setOriginalDelay(delay);
                    newGroupSendMsgDto.setRetry(0);
                    newGroupSendMsgDto.setLabel(groupSendJobChild.getUserLab());
                    newGroupSendMsgDto.setRemark(groupSendJobChild.getUserRemark());
                    //群发助手
                    newGroupSendMsgDto.setGroupSendType(groupSendJobChild.getGroupSendType());
                    //封装群发会员列表
                    newGroupSendMsgDto.setGroupSendUserInfos(groupSendUserInfoList);
                    //临时封装发送消息对象列表
                    List<NewGroupSendMsgDto> newGroupSendMsgDtoList = new ArrayList<>();
                    newGroupSendMsgDtoList.add(newGroupSendMsgDto);
                    //调用微服务批量发送消息
                    UzaiRespVo<Boolean>  uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                    if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                        //实际发送总数累加
                        sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                        //清空封装的会员列表
                        groupSendUserInfoList.clear();
                        //logger.info("----通讯录新建群发消息任务---para={}, size={}. result={}", JSONObject.toJSONString(wxContactsQuery), newGroupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                    }else{
                        logger.error("----通讯录新建群发消息任务失败---size={}", newGroupSendMsgDtoList.size());
                        //失败的在调用一次,再次失败则修改群发消息条数
                        UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(newGroupSendMsgDtoList);
                        if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                            //实际发送总数累加
                            sendMsgTotal_real = sendMsgTotal_real + groupSendUserInfoList.size();
                            //清空封装的会员列表
                            groupSendUserInfoList.clear();
                        }else{
                            //最后也会清空封装的会员列表
                            groupSendUserInfoList.clear();
                        }
                    }
                }
            }

            //修改子任务发送总数
            groupSendJobChild.setFinishCount(0);
            groupSendJobChild.setFinishCountSnapshot(0);
            groupSendJobChild.setTotalCount(sendMsgTotal_real);
            groupSendJobMapper.updateByIdSelective(groupSendJobChild);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJobChild.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJobChild.getTimeInterval());
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }
    }

    /**
     * 导出记录数和总金额
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxContactsQuery
     */
    public ExportAmountVo getExportAmount(WxContactsQuery wxContactsQuery){

        if(wxContactsQuery.getDeviceUniqueIdList() == null && wxContactsQuery.getDeviceUniqueIdList().size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择机器人");
        }

        wxContactsQuery.setUserType(0); //个人微信通讯录

        //单个机器人查询总数
        long totalCount = searchTotal(wxContactsQuery);
        if(totalCount == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果记录数为0");
        }

        if(totalCount >= ESConstant.TOTAL_MAX) { //大于1万条，不支持导出
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询结果总数超过1万条");
        }

        String price = sysConfigMapper.selectByKey("export_record_price");

        ExportAmountVo  exportAmountVo = new ExportAmountVo();
        exportAmountVo.setAmountTotal(1.00);
        exportAmountVo.setCountTotal(totalCount);
        exportAmountVo.setPrice(Double.parseDouble(price));

        return exportAmountVo;

    }

    /**
     * 批量同步微信备注到用户列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    @Async("taskExecutor")
    public void batchRefreshUserRemark(WxContactsBatchRefreshUserRemarkDto wxContactsBatchRefreshUserRemarkDto){
        //查询通讯录
        int currentPage = 1; //当前页
        int size = 20;
        //查询总用户数
        WxContactsQuery wxContactsQuery = new WxContactsQuery();
        wxContactsQuery.setMerId(wxContactsBatchRefreshUserRemarkDto.getMerId());
        wxContactsQuery.setDeviceUniqueId(wxContactsBatchRefreshUserRemarkDto.getDeviceUniqueId());
        wxContactsQuery.setSize(size);
        wxContactsQuery.setCurrent(currentPage);

        Page<WxContactsInfoVo> wxContactsInfoVoPage = findWxContactsList(wxContactsQuery, false);
        while(wxContactsInfoVoPage != null && wxContactsInfoVoPage.getRecords() != null && wxContactsInfoVoPage.getRecords().size() > 0){
            //发送消息
            for(WxContactsInfoVo wxContactsInfoVo : wxContactsInfoVoPage.getRecords()){
                try {
                    //会员信息
                    if(wxContactsInfoVo.getUserId() != null){
                        WechatUser wechatUser = wechatUserMapper.selectById(wxContactsInfoVo.getUserId(), wxContactsInfoVo.getMerId());
                        if(wechatUser != null){ //找到会员信息，才更新备注
                            wechatUser.setRemark(wxContactsInfoVo.getRemark());
                            wechatUserMapper.updateRemarkAndTags(wechatUser);
                        }
                    }
                }catch (Exception e){
                    logger.error("修改会员备注失败，error={}", e.getMessage());
                }
            }

            currentPage ++ ; //页码+1
            wxContactsQuery.setCurrent(currentPage);
            wxContactsInfoVoPage = findWxContactsList(wxContactsQuery, false);
        }
    }

    /**
     * 删除单个机器人的通讯录
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param merId
     * @return null
     */
    public void deleteWxContactsByDeviceUniqueId(Long deviceUniqueId, Long merId){
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        //清空所有的发送明细
        SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_and = new BoolQueryBuilder();
        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", merId));
        //机器人唯一id
        boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
        searchSourceBuilder_del.query(boolQuery_and).size(100);
        deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_wx_contacts, deleteByQueryRequest);
    }

    /**
     * 通讯录批量删除
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wxContactsQuery
     * @return null
     */
    public void batchDeleteSync(WxContactsQuery wxContactsQuery){
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        //清空所有的发送明细
        SearchSourceBuilder searchSourceBuilder_del = new SearchSourceBuilder();

        BoolQueryBuilder boolQuery_and = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery_and.must(QueryBuilders.termQuery("merId", Tools.getLong(wxContactsQuery.getMerId())));

        //好友类型(0-个人微信；1-微信群)
        if(wxContactsQuery.getUserType() != null){
            boolQuery_and.must(QueryBuilders.termQuery("userType", wxContactsQuery.getUserType()));
        }

        //高亮字段
        String highlightField = null;

        //微信昵称
        if(StringUtils.isNotBlank(wxContactsQuery.getNick())){
            boolQuery_or.should(QueryBuilders.matchQuery("nick", wxContactsQuery.getNick()));
            boolQuery_or.should(QueryBuilders.termQuery("nick.raw", wxContactsQuery.getNick()));
            //highlightField = "nick";
        }

        //微信id
        if(StringUtils.isNotBlank(wxContactsQuery.getWxid())){
            boolQuery_and.must(QueryBuilders.termQuery("wxid",wxContactsQuery.getWxid()));
            //highlightField = "wxid";
        }

        //微信号
        if(StringUtils.isNotBlank(wxContactsQuery.getWxno())){
            boolQuery_and.must(QueryBuilders.termQuery("wxno",wxContactsQuery.getWxno()));
            //highlightField = "wxno";
        }


        //机器人唯一ID
        if(wxContactsQuery.getDeviceUniqueId() != null){
            boolQuery_and.must(QueryBuilders.termQuery("deviceUniqueId",wxContactsQuery.getDeviceUniqueId()));
        }

        //机器人唯一id列表
        if(wxContactsQuery.getDeviceUniqueIdList() != null && wxContactsQuery.getDeviceUniqueIdList().size() > 0){
            boolQuery_and.must(QueryBuilders.termsQuery("deviceUniqueId", wxContactsQuery.getDeviceUniqueIdList()));
        }

        //最后群发消息开始时间
        if(wxContactsQuery.getLastGroupSendTimeStart() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").gte(wxContactsQuery.getLastGroupSendTimeStart()));
        }

        //最后群发消息结束时间
        if(wxContactsQuery.getLastGroupSendTimeEnd() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lte(wxContactsQuery.getLastGroupSendTimeEnd()));
        }

        //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)
        if(wxContactsQuery.getBusyGroupSendMsgTime() != null){
            boolQuery_and.must(QueryBuilders.rangeQuery("lastGroupSendTime").lt(wxContactsQuery.getBusyGroupSendMsgTime()));
        }

        //子账号绑定机器人
        List<Long> subDeviceUniqueIdList = wxContactsQuery.getSubDeviceUniqueIdList();
        if(subDeviceUniqueIdList != null && subDeviceUniqueIdList.size() > 0){
            for (Long deviceUniqueId : subDeviceUniqueIdList) {
                boolQuery_or.should(QueryBuilders.termQuery("deviceUniqueId", deviceUniqueId));
            }
        }

        searchSourceBuilder_del.query(boolQuery_and.must(boolQuery_or)).size(100);
        deleteByQueryRequest.getSearchRequest().source(searchSourceBuilder_del);
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        elasticsearchUtilGroupMsg.deleteDataByQueryMulti(uzai_wx_contacts, deleteByQueryRequest);
    }

}
